package com.browsesoft;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 系统配置
 */
public class SystemConfig extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5924520951936020017L;

	Element element;

	JTextField text;

	LinkedList changeFiles = new LinkedList();

	String value;

	public SystemConfig() {
	}

	public SystemConfig(Element e, String path) {
		element = e;
		this.add(new JLabel(e.getAttribute("title")));
		String type = e.getAttribute("type");
		if (type.equals("text")) {
			value = e.getAttribute("value").trim();
			text = new JTextField(value + "    ");
			this.add(text);
		}
		NodeList ls = e.getElementsByTagName("change");
		for (int i = 0; i < ls.getLength(); i++) {
			Element change = (Element) ls.item(i);
			this.changeFiles.add(new ChangeFile(change, path));
		}
	}

	public String getLableName() {
		return this.element.getAttribute("title");
	}

	public void save() throws Exception {
		String value = this.text.getText().trim();
		if (!this.value.trim().equals(value)) {
			this.value = value;
			this.element.setAttribute("value", value);
			Iterator iter = this.changeFiles.iterator();
			while (iter.hasNext()) {
				ChangeFile item = (ChangeFile) iter.next();
				item.save(value);
			}
		}
	}

	public JTextField getField() {
		return text;
	}
}

class ChangeFile {
	Element element;

	String path;

	public ChangeFile(Element e, String path) {
		this.element = e;
		this.path = path;
	}

	public void save(String value) throws Exception {
		FileService file = new FileService(path + this.get("path"));
		Element content = file.getElment(this.get("tagname"), Integer
				.parseInt(this.get("position")));
		content.setAttribute(this.get("change"), value);
		OutputStream os = new FileOutputStream(file.getFile());
		os.write("<?xml version='1.0' encoding='GB2312'?>".getBytes());
		os.write(file.getDocument().getDocumentElement().toString().getBytes());
		os.flush();
		os.close();
	}

	public String get(String name) {
		return this.element.getAttribute(name);
	}
}